import { NIcon, NLayoutSider, NMenu } from 'naive-ui'
import { computed, defineComponent } from 'vue'
import { MenuMixedOption } from 'naive-ui/lib/menu/src/interface'
import styles from './SiderMenu.module.scss'
import Logo from '../Icon'
import { useAppStore } from '@/store/modules/app'
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@vicons/antd'
import { usePermissionStore } from '@/store/modules/permission'
import { RouteRecordRaw, RouterLink, useRoute } from 'vue-router'
import { CodeDownloadOutline } from '@vicons/ionicons5'

// !此方法需自行实现
const renderIcon = () => {
  // 自定义实现图标
  return () => (
    <NIcon>
      <CodeDownloadOutline />
    </NIcon>
  )
}

// todo 递归渲染菜单
function renderMenu(route: RouteRecordRaw) {
  const result: MenuMixedOption = {
    label: () => LinkMenu(route),
    key: route.path,
  }
  // ? 如果icon存在，则使用icon =》 renderIcon 方法根据实际需求实现
  route.meta?.icon && (result.icon = renderIcon())
  // result.icon = renderIcon()

  // ? 如果有子路由，则递归调用
  route.children && (result.children = route.children.map(v => renderMenu(v)))
  return result
}

const SiderMenu = defineComponent(() => {
  const appStore = useAppStore()
  const permissionStore = usePermissionStore()

  // todo LOGO组件
  const LogoComponent = () => {
    return (
      <div class={[styles.logo_wrap, appStore.menuTrigger && styles.hide_title]}>
        <Logo />
        <div class={styles.logo_title}>{import.meta.env.VITE_APP_TITLE}</div>
      </div>
    )
  }

  // todo 底部菜单开关
  const TriggerComponent = () => (
    <div class={[styles.trigger_wrap]}>
      <div onClick={() => (appStore.menuTrigger = !appStore.menuTrigger)}>
        <NIcon class="cursor-pointer" size={26}>
          {appStore.menuTrigger ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </NIcon>
      </div>
    </div>
  )

  const routes = computed<MenuMixedOption[]>(function () {
    return permissionStore.asyncRoutes.map(v => renderMenu(v))
  })
  const router = useRoute()
  return () => (
    <NLayoutSider
      nativeScrollbar={false}
      collapsed={appStore.menuTrigger}
      collapseMode="width"
      collapsedWidth={64}
      bordered
      class={[appStore.menuPosition === 'bottom' && styles.sider_menu_wrap_bottom]}
      width={appStore.menuWidth}
      showTrigger={appStore.menuShowTrigger && appStore.menuPosition === 'left'}
      onExpand={() => (appStore.menuTrigger = false)}
      onCollapse={() => (appStore.menuTrigger = true)}
    >
      <LogoComponent />
      <NMenu
        options={routes.value}
        accordion={appStore.menuAccordion}
        class={styles.menu}
        collapsed={appStore.menuTrigger}
        collapsedWidth={64}
        value={router.path}
      />
      <TriggerComponent />
    </NLayoutSider>
  )
})

const LinkMenu = (record: RouteRecordRaw) => {
  if (record.meta?.disable) return record.meta?.title

  return <RouterLink to={{ path: record.path }}>{record.meta?.title}</RouterLink>
}

export default SiderMenu
